import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/pages/mixin/web_view_mixin.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../l10n/local.dart';
import '../../../routes/app_routes.dart';
import '../../../service/cache_config_service.dart';
import '../../../service/global_service.dart';
import '../../../service/translation_service.dart';
import '../../../utils/package_info_util.dart';
import '../../mixin/cache_mixin.dart';
import '../../mixin/vehicle_type_mixin.dart';
import '../../models/settting_item_model.dart';
import 'state.dart';

class MineSettingController extends GetxController
    with WebViewMixin, CacheMixin, RealtimeInfoMixin {
  // 状态
  final MineSettingState state = MineSettingState();

  // 车辆类型
  final VehicleType _vehicleType = GlobalService.to.currentVehicleType;

  @override
  void onInit() {
    super.onInit();
    _reloadData();
  }

  // 重新加载数据
  _reloadData() {
    // 初始化功能列表
    state.itemList.value = _vehicleType.mineSettingCellList();
    // 赋值OnTap事件
    for (int i = 0; i < state.itemList.length; i++) {
      for (int j = 0; j < state.itemList[i].subItems.length; j++) {
        _setCellOnTap(state.itemList[i].subItems[j]);
      }
    }
  }

  // 设置页面cell点击事件
  _setCellOnTap(SettingRowModel model) async {
    if (model.title == local.unit_metric_imperial) {
      // 公英制单位切换
      model.value = CacheConfigService.to.isMetric
          ? local.unit_metric
          : local.unit_imperial;
      model.onTap = () {
        _setUnitMetricImperial(model.value ?? "").then((success) {
          if (success) {
            Loading.showSuccess(local.setting_successful);
          } else {
            Loading.showError(local.setting_failed);
          }
          _setCellOnTap(model);
        }).catchErrorHandler();
      };
    } else if (model.title == local.language) {
      // 语言切换
      model.value = TranslationService.getLocale().languageCode == 'zh'
          ? local.ZH
          : local.EN;
      model.onTap = () {
        _setLanguage(model.value ?? "").then((success) {
          Loading.showSuccess(local.setting_successful);
          Get.offAllNamed(AppRoutes.ROOT);
        }).catchErrorHandler();
      };
    } else if (model.title == local.account_security) {
      // 账号安全
      model.onTap = () {
        Get.toNamed(AppRoutes.ACCOUNT_SECURITY);
      };
    } else if (model.title == local.clear_cache) {
      String cacheSize = await _getCacheSize();
      model.value = cacheSize;
      debugPrint('缓存大小: $cacheSize');
      // 清理缓存
      model.onTap = () {
        Loading.showLoading(local.clear_cache);
        _clearCacheOnTap().then((_) {
          _setCellOnTap(model);
          Loading.showSuccess(local.clear_cache_success);
        }).catchErrorHandler();
      };
    } else if (model.title == local.app_about) {
      // 版本号/构建号
      String version = await PackageInfoUtil.getAppVersion();
      String buildNumber = await PackageInfoUtil.getBuildNumber();
      model.value = '$version($buildNumber)';
      // 关于App
      model.onTap = () {
        Get.toNamed(AppRoutes.APP_ABOUT, arguments: model.value);
      };
    }
    state.itemList.refresh();
  }

  // 设置公英制单位
  Future<bool> _setUnitMetricImperial(String currentUnit) async {
    List<(String, int)> list = [
      (local.unit_metric, 0),
      (local.unit_imperial, 1),
    ];
    Completer<bool> completer = Completer<bool>();
    int selectedIndex = list.indexWhere((element) => element.$1 == currentUnit);
    LxBottomSheet.show(
      Get.context!,
      title: "${local.settings}${local.unit_metric_imperial}",
      contentColor: Colors.white,
      selectIndex: selectedIndex,
      dataArr: list.map((e) => e.$1).toList(),
      cancelTitle: local.cancel,
      selectedCallback: (int index, String? selectedStr) {
        Loading.showLoading(null);
        Future.delayed(const Duration(milliseconds: 700)).then((_) {
          CacheConfigService.to
              .setMetricUnit(list[index].$1 == local.unit_metric)
              .then((success) {
            if (success) {
              if (!completer.isCompleted) {
                completer.complete(true);
              }
            } else {
              if (!completer.isCompleted) {
                completer.complete(false);
              }
            }
          }).catchError((error) {
            if (!completer.isCompleted) {
              completer.completeError(error);
            }
          });
        });
      },
    );
    return completer.future;
  }

  // 设置语言
  Future<bool> _setLanguage(String currentLanguage) async {
    List<(String, int)> list = [
      (local.ZH, 0),
      (local.EN, 1),
    ];
    Completer<bool> completer = Completer<bool>();
    int selectedIndex =
        list.indexWhere((element) => element.$1 == currentLanguage);
    LxBottomSheet.show(
      Get.context!,
      title: "${local.settings}${local.language}",
      contentColor: Colors.white,
      selectIndex: selectedIndex,
      dataArr: list.map((e) => e.$1).toList(),
      cancelTitle: local.cancel,
      selectedCallback: (int index, String? selectedStr) {
        Loading.showLoading(local.setting_language);
        Future.delayed(const Duration(milliseconds: 700)).then((_) {
          TranslationService.changeLocale(
                  Locale(list[index].$1 == local.ZH ? 'zh' : 'en'))
              .then((success) {
            if (!completer.isCompleted) {
              // 同步设置语言到【售后服务】插件中
              AppLanguageUtil.setLanguage(
                  type: list[index].$1 == local.ZH
                      ? LanguageType.cn
                      : LanguageType.en);
              completer.complete(true);
            }
          }).catchError((error) {
            if (!completer.isCompleted) {
              completer.completeError(error);
            }
          });
        });
      },
    );
    return completer.future;
  }

  // 获取缓存大小
  Future<String> _getCacheSize() async {
    return PackageInfoUtil.calculateCacheSize().then((size) {
      return PackageInfoUtil.formatSize(size);
    }).then((sizeStr) {
      debugPrint('缓存大小: $sizeStr');
      return sizeStr;
    });
  }

  // 清理缓存
  Future<void> _clearCacheOnTap() async {
    return Future.delayed(const Duration(milliseconds: 700))
        .then((value) => PackageInfoUtil.clearCache());
  }
}
